<?php

namespace App\Imports\DomainInduce;

use App\Models\Domain\Induce\ExcelQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Log;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Maatwebsite\Excel\Concerns\RemembersChunkOffset;
use Maatwebsite\Excel\Concerns\SkipsOnError;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\Importable;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithUpserts;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Events\AfterImport;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Events\BeforeImport;
use Maatwebsite\Excel\Validators\Failure;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
use Throwable;

HeadingRowFormatter::default('none');

class Info implements ToModel, WithHeadingRow, WithUpserts, WithValidation, WithChunkReading, ShouldQueue, WithEvents,
    SkipsOnError,
    SkipsOnFailure {

    use Importable;                     //具有importg功能

    use RemembersChunkOffset;          //偏移量的信息
    // use SkipsErrors;               //跳过所有错误
    // use SkipsFailures;            //跳过所有失败
    use RegistersEventListeners;     //监听事件
    private $end_time;
    private $total_count;
    private $current_count;
    private $excel_queue;


    public function model(array $row) {
        return new \App\Models\Domain\Induce\Info([
            'domain' => $row['域名'] ?? null,
            'self_self' => $row['自持'] ?? null,
            'self_price' => $row['成本'] ?? null,

            'testing_qq' => $row['QQ检测'] ?? null,
            'testing_wechat' => $row['微信检测'] ?? null,
            'testing_condition' => $row['被墙/污染'] ?? null,

            'sougou_shourushu' => $row['搜狗收录'] ?? null,
            'sougou_title' => $row['搜狗标题'] ?? null,
            'sougou_describe' => $row['搜狗描述'] ?? null,
            'sougou_snapshot' => $row['快照时间'] ?? null,
            'sougou_pr_old' => $row['搜狗PR【历史】'] ?? null,
            'sougou_re_link' => $row['搜狗反链'] ?? null,
            'sougou_official' => $row['搜狗官网'] ?? null,
            'sougou_news_source' => $row['新闻源'] ?? null,

            'old_age' => $row['年龄'] ?? null,
            'old_count' => $row['数量'] ?? null,
            'old_last' => $row['最老'] ?? null,
            'old_new' => $row['最新'] ?? null,
            'old_chines' => $row['中文'] ?? null,
            'old_percent' => $row['占比'] ?? null,
            'old_unified_percent' => $row['统一度'] ?? null,
            'old_year_5' => $row['五年建站'] ?? null,
            'old_language' => $row['语言'] ?? null,
            'old_label' => $row['标记'] ?? null,
            'old_keyword' => $row['关键词'] ?? null,
            'old_year_sort' => $row['年排序'] ?? null,
            'old_title' => $row['标题'] ?? null,
            'old_remarks' => $row['历史备注'] ?? null,

            'icp_company' => $row['单位名称'] ?? null,
            'icp_type' => $row['单位性质'] ?? null,
            'icp_num' => $row['ICP备案号'] ?? null,
            'icp_region' => $row['备案地区'] ?? null,
            'icp_site_name' => $row['网站名称'] ?? null,
            'icp_audit_time' => $row['审核时间'] ?? null,
            'icp_provider' => $row['接入商'] ?? null,
            'icp_status' => $row['状态'] ?? null,
            'icp_blacklist' => $row['备案黑名单'] ?? null,
            'icp_police' => $row['备案地公安机关'] ?? null,
            'icp_multi' => $row['批量备案'] ?? null,

            'base_delete_type' => $row['删除类型'] ?? null,
            'base_delete_day' => $row['删除日期'] ?? null,
            'base_suffix' => $row['后缀'] ?? null,
            'base_email' => $row['邮箱'] ?? null,
            'base_people' => $row['注册人'] ?? null,
            'base_registrant' => $row['注册商'] ?? null,
            'base_reg_day' => $row['注册时间'] ?? null,
            'base_end_day' => $row['到期时间'] ?? null,
            'base_reg_age' => $row['注册年龄'] ?? null,
            'base_old' => $row['是否老域名'] ?? null,
            'base_available_day' => $row['可用天数'] ?? null,
            'base_status' => $row['域名状态'] ?? null,

            'baidu_included' => $row['百度收录量'] ?? null,
            'baidu_grey' => $row['百度灰'] ?? null,
            'baidu_safe' => $row['百度安全'] ?? null,
            'baidu_official' => $row['百度官网'] ?? null,
            'baidu_v_log' => $row['百度V认证'] ?? null,
            'baidu_evaluate' => $row['百度评价'] ?? null,
            'baidu_weight' => $row['百度权重'] ?? null,
            'baidu_re_link' => $row['百度反链'] ?? null,
            'baidu_testing' => $row['百度检测'] ?? null,
            'baidu_re_amount' => $row['反向链接数量'] ?? null,
            'baidu_high_weight_5' => $row['高权重5+'] ?? null,
            'baidu_gov' => $row['Gov外链'] ?? null,
            'baidu_edu' => $row['edu外链'] ?? null,

            '360_included' => $row['360收录'] ?? null,
            '360_weight' => $row['360权重'] ?? null,
            '360_official' => $row['360官网'] ?? null,
        ]);
    }


//    public function batchSize(): int
//    {
//        return 10000;
//    }

    public function chunkSize(): int {
        //  return env('IMPORT_QUEUE_CHUNK_SIZE', 1000);
        return config('app.excel_queue.chunk_size', 5000);
    }

    public function uniqueBy() {
        //唯一字段
        return 'domain';
    }

    public function prepareForValidation($data, $index) {
        //处理字符
        foreach ($data as $key => $value) {
            $temp = trim(str_replace(' ', '', $value));
            if ($key == '快照时间') {
                $temp = (int) $temp;
                $n = (($temp - 25569) * 3600 * 24); //转换成1970年以来的秒数
                $temp = gmdate('Y-m-d', $n);//时区相差8小时
            }
            if ($key == '审核时间') {
                $temp = (int) $temp;
                $n = (($temp - 25569) * 3600 * 24); //转换成1970年以来的秒数
                $temp = gmdate('Y', $n);//时区相差8小时
            }
            if ($key == '自持') {
                $temp = $temp == '是' ? true : false;
            }
            if ($key == '成本') {
                $temp = (int) $temp;
            }
            if ($key == 'QQ检测') {
                switch ($temp) {
                    case '正常':
                        $temp = 1;
                        break;
                    case '拦截':
                        $temp = 2;
                        break;
                    case '已认证':
                        $temp = 3;
                        break;
                    default:
                        $temp = 0;
                }
            }
            if ($key == '微信检测') {
                switch ($temp) {
                    case '正常':
                        $temp = 1;
                        break;
                    case '拦截':
                        $temp = 2;
                        break;
                    case '长按复制访问':
                        $temp = 3;
                        break;
                    case '提示跳转':
                        $temp = 4;
                        break;
                    default:
                        $temp = 0;
                }
            }
            if ($key == '搜狗收录') {
                $temp = (int) $temp;
            }
            if ($key == '被墙/污染') {
                switch ($temp) {
                    case '正常':
                        $temp = 1;
                        break;
                    case '被墙':
                        $temp = 2;
                        break;
                    case '污染':
                        $temp = 3;
                        break;
                    default:
                        $temp = 0;
                }
            }

            if ($key == '搜狗PR【历史】') {
                $temp = (int) $temp;
            }
            if ($key == '搜狗反链') {
                $temp = (int) $temp;
            }
            if ($key == '搜狗官网') {
                $temp = $temp == '搜狗官网' ? true : false;
            }
            if ($key == '新闻源') {
                $temp = $temp == '是' ? true : false;
            }

            if ($key == '年龄') {
                $temp = (int) $temp;
            }
            if ($key == '数量') {
                $temp = (int) $temp;
            }
            if ($key == '最老') {
                $temp = (int) $temp;
            }
            if ($key == '最新') {
                $temp = (int) $temp;
            }
            if ($key == '中文') {
                $temp = (int) $temp;
            }
            if ($key == '五年建站') {
                $temp = (int) $temp;
            }

            if ($key == '占比') {
                $temp = trim(str_replace('%', '', $temp));
            }
            if ($key == '统一度') {
                $temp = trim(str_replace('%', '', $temp));
            }
            if ($key == '历史备注') {
                switch ($temp) {
                    case '正常':
                        $temp = 1;
                        break;
                    case '灰色':
                        $temp = 2;
                        break;
                    default:
                        $temp = 0;
                }
            }
            if ($key == '状态') {
                switch ($temp) {
                    case '当前存在':
                        $temp = 1;
                        break;
                    case '历史存在':
                        $temp = 2;
                        break;
                    default:
                        $temp = 0;
                }
            }
            if ($key == '备案黑名单') {
                $temp = $temp == '正常' ? true : false;
            }
            if ($key == '批量备案') {
                $temp = $temp == '是' ? true : false;
            }
            if ($key == '删除日期') {
                $temp = $temp == '' ? null:$temp;
            }

            if ($key == '注册年龄') {
                $temp = (int) $temp;
            }
            if ($key == '是否老域名') {
                $temp = $temp == '是' ? true : false;
            }
            if ($key == '可用天数') {
                $temp = (int) $temp;
            }
            if ($key == '百度收录量') {
                $temp = (int) $temp;
            }
            if ($key == '百度安全') {
                switch ($temp) {
                    case '百度安全':
                        $temp = 1;
                        break;
                    case '安全中心拦截':
                        $temp = 2;
                        break;
                    case '危险':
                        $temp = 3;
                        break;
                    default:
                        $temp = 0;
                }
            }
            if ($key == '百度官网') {
                $temp = $temp == '百度官网' ? true : false;
            }
            if ($key == '百度V认证') {
                $temp = $temp == '已认证' ? true : false;
            }
            if ($key == '百度评价') {
                $temp = $temp == '有评价' ? true : false;
            }
            //
            if ($key == '百度权重') {
                $temp = (int) $temp;
            }
            if ($key == '百度反链') {
                $temp = (int) $temp;
            }
            if ($key == '百度检测') {
                $temp = (int) $temp;
            }
            if ($key == '反向链接数量') {
                $temp = (int) $temp;
            }
            if ($key == '高权重5+') {
                $temp = (int) $temp;
            }
            if ($key == 'Gov外链') {
                $temp = (int) $temp;
            }
            if ($key == 'edu外链') {
                $temp = (int) $temp;
            }
            if ($key == '360收录') {
                $temp = (int) $temp;
            }
            if ($key == '360权重') {
                $temp = (int) $temp;
            }
            if ($key == '360官网') {
                $temp = $temp == '360官网' ? true : false;
            }

            $data[$key] = $temp;
        }

        return $data;
    }


    public function rules(): array {
        // TODO: Implement rules() method.
        return [
            //   'email' => ['required']
            //  'email' => ['unique', 'unique:DomainInfo,email']

        ];
    }

    public function registerEvents(): array {
        return [
            BeforeImport::class => function (BeforeImport $event) {
                $this->end_time = microtime(true);
                $this->total_count = array_sum($event->reader->getTotalRows());
                $test = ExcelQueue::where('queue_name', '域名归纳')
                    ->where('type', 1)->update(['total_chunk' => $this->total_count, 'remarks' => '导入中...']);
                //$test->total_chunk = $test->total_chunk + 1;
                //  $test->total_chunk->save();
                echo '开始 ---- 总块数:'.$this->total_count.PHP_EOL;


            },
            AfterImport::class => function (AfterImport $event) {
                $this->end_time = microtime(true) - $this->end_time;


                \Storage::delete('public/upload/excel/import.xlsx');  //删除文件

                ExcelQueue::where('queue_name', '域名归纳')
                    ->where('type', 1)->update([
                        'status' => true, 'remarks' => '完成耗时:'.number_format($this->end_time).' 秒'
                    ]);
                echo '完成耗时: '.number_format($this->end_time, 4).PHP_EOL;

            },
            AfterSheet::class => function (AfterSheet $event) {
                $this->current_count = $event->getConcernable()->chunkOffset;
                ExcelQueue::where('queue_name', '域名归纳')
                    ->where('type', 1)->update(['current_chunk' => $this->current_count]);
                echo '当前进度: '.$this->total_count.'/'.$this->current_count.PHP_EOL;
            },
        ];
    }


    /**
     * @param  Throwable  $e
     */
    public function onError(Throwable $e) {
        // TODO: Implement onError() method.
        //  var_dump('onError',$e->getMessage());
        //   var_dump('onError');
        Log::channel('excel')->info('onError', ['file' => $e->getFile(), $e->getMessage()]);
    }

    /**
     * @param  Failure[]  $failures
     */
    public function onFailure(Failure ...$failures) {
        // TODO: Implement onFailure() method.
        //  var_dump($failures[0]->errors());
        Log::channel('excel')->info('onFailure', $failures);
    }
}
